package demo;

import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.comments.JavadocComment;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import com.lkcoffee.demo.domain.ColMappingDto;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import static com.lkcoffee.demo.utils.SqlToMarkdownUtils.writeMarkdownFile;

public class JavadocToMarkdown {

    private static final String JAVA_FILE_PATH = "D:\\code\\java-test\\demo1\\src\\main\\java\\com\\lkcoffee\\demo\\test\\InventoryAllocationDTO.java";

    private static final String MARKDOWN_FILE_PATH = "D:\\code\\java-test\\demo1\\src\\main\\resources";


    public static void main(String[] args) throws IOException {
        File sourceFile = new File(JAVA_FILE_PATH);
        JavaParser parser = new JavaParser();
        ParseResult<CompilationUnit> parseResult = parser.parse(sourceFile);
        if (!parseResult.isSuccessful()) {
            System.err.println("Parse error: " + parseResult.getProblems());
            return;
        }
        List<ColMappingDto> list=new ArrayList<>();
        CompilationUnit cu = parseResult.getResult().get();
        cu.accept(new VoidVisitorAdapter<Void>() {
            @Override
            public void visit(FieldDeclaration n, Void arg) {
                super.visit(n, arg);
                JavadocComment javadoc = n.getJavadocComment().orElse(null);
                if (javadoc != null) {
                    VariableDeclarator variableDeclarator = n.getVariables().get(0);
                    ColMappingDto colMappingDto=new ColMappingDto();
                    colMappingDto.setType(variableDeclarator.getType().toString());
                    colMappingDto.setComment(javadoc.getContent().trim().replaceFirst("^\\*\\s+", ""));
                    colMappingDto.setName(variableDeclarator.getNameAsString());
                    list.add(colMappingDto);
                }
            }
        }, null);
        String className = cu.getPrimaryType().get().getNameAsString();
        Path path = Paths.get(MARKDOWN_FILE_PATH, className + ".md");
        writeMarkdownFile(path.toString(),list);
    }

}
